from fastapi import Request
from sqlalchemy.ext.asyncio import AsyncSession
from exceptions.exception import ServiceException
from module_admin.dao.machine_dao import MachineDao
from module_admin.entity.vo.machine_vo import MachinePageQueryModel
from module_admin.entity.vo.machine_vo import MachineModel
from module_admin.entity.vo.common_vo import CrudResponseModel
from utils.common_util import CamelCaseUtil
from utils.log_util import logger

class MachineService:
    """
    机台管理模块服务层
    """

    @classmethod
    async def get_list_services(
        cls, query_db: AsyncSession, query_object: MachinePageQueryModel, data_scope_sql: str, is_page: bool = False
    ):
        """
        获取机台列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param data_scope_sql: 数据权限对应的查询sql语句
        :param is_page: 是否开启分页
        :return: 机台列表信息对象
        """
        # 获取数据
        query_result = await MachineDao.get_machine_list(query_db, query_object, data_scope_sql, is_page)

        return query_result
    
    @classmethod
    async def detail_services(cls, query_db: AsyncSession, id: int):
        """
        获取详细信息service

        :param query_db: orm对象
        :param id: id
        :return: id对应的信息
        """
        detail = await MachineDao.get_detail_by_id(query_db, id=id)
        if detail:
            result = MachineModel(**CamelCaseUtil.transform_result(detail))
        else:
            result = MachineModel(**dict())

        return result

    @classmethod
    async def add_services(cls, request: Request, query_db: AsyncSession, page_object: MachineModel):
        """
        新增service

        :param request: Request对象
        :param query_db: orm对象
        :param page_object: 新增对象
        :return: 新增结果
        """
        try:
            await MachineDao.add_dao(query_db, page_object)
            await query_db.commit()
            result = dict(is_success=True, message='新增成功')
            return CrudResponseModel(**result)
        except Exception as e:
            await query_db.rollback()
            raise e
    
    @classmethod
    async def edit_services(cls, request: Request, query_db: AsyncSession, page_object: MachineModel):
        """
        编辑信息service

        :param request: Request对象
        :param query_db: orm对象
        :param page_object: 编辑对象
        :return: 编辑结果
        """
        # logger.info(f'page_object: {page_object}')
        edit_model = page_object.model_dump(exclude_none=True)
        # edit_model = page_object.model_dump(exclude_unset=True)
        detail_info = await cls.detail_services(query_db, page_object.id)
        if detail_info.id:
            try:
                await MachineDao.edit_dao(query_db, edit_model)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='更新成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='修改对象不存在')

    @classmethod
    async def delete_services(
        cls, request: Request, query_db: AsyncSession, ids: str
    ):
        """
        删除信息service

        :param request: Request对象
        :param query_db: orm对象
        :param page_object: 删除对象
        :return: 删除结果
        """
        if ids:
            id_list = ids.split(',')
            try:
                delete_list = []
                for id in id_list:
                    oneId = await cls.detail_services(query_db, int(id))
                    await MachineDao.delete_dao(query_db, MachineModel(id=id))
                    delete_list.append(oneId.machine_id)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message=f'{delete_list}删除成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='传入id为空')
        
    @classmethod
    async def get_machine_select_services(cls, query_db: AsyncSession, page_object: MachineModel, data_scope_sql: str):
        """
        获取机台信息service

        :param query_db: orm对象
        :param page_object: 查询参数对象
        :param data_scope_sql: 数据权限对应的查询sql语句
        :return: 部门机台列表对象
        """
        logger.info(f'page_object: {page_object}')
        search_list_result = await MachineDao.get_machine_select_list(query_db, page_object, data_scope_sql)

        return search_list_result